package cn.snsprj.authserver.interceptor;

import cn.snsprj.authserver.common.ConstCode.ConstCodeUrl;
import cn.snsprj.authserver.common.Router.RouterLogin;
import cn.snsprj.authserver.util.URLUtil;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 *
 * 权限拦截器
 * @author SKH
 * @date 2018-08-20 10:06
 **/
@Component
public class AuthInterceptor implements HandlerInterceptor{


    private Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {


        String requestURI = request.getRequestURI();
        logger.info("====>request uri is {}", requestURI);

        // 去除第一个斜杠
        requestURI = StringUtils.substringAfter(requestURI, "/");

        // 判断是否为请求静态资源
        Set<String> resourceSuffixSet = new HashSet<>();
        resourceSuffixSet.add("ico");
        resourceSuffixSet.add("xml");
        resourceSuffixSet.add("json");
        resourceSuffixSet.add("xlsx");
        resourceSuffixSet.add("js");
        resourceSuffixSet.add("html");
        resourceSuffixSet.add("css");

        String suffix = StringUtils.substringAfterLast(requestURI, ".");
        if (resourceSuffixSet.contains(suffix)) {
            logger.info("====>suffix is {}", suffix);
            return true;
        }

        String prefix = StringUtils.substringBefore(requestURI, "/");
        logger.info("====>prefix is {}", prefix);

        // 列外的url
        Set<String> exceptURLSet = new HashSet<>();
        exceptURLSet.add("auth");
        exceptURLSet.add("login");
        exceptURLSet.add("logout");
        exceptURLSet.add("verify_st");

        if (exceptURLSet.contains(prefix)) {
            // 无需拦截的url
            return true;
        }else {
            Cookie[] cookies = request.getCookies();
            if (cookies == null || cookies.length == 0) {

                logger.info("====> cookie is null, uri is {}", requestURI);

                HttpSession session = request.getSession();
                String sourceUrl = request.getParameter(ConstCodeUrl.URL_KEY_SOURCE_URL);
                // 把sourceUrl存储到session
                session.setAttribute(ConstCodeUrl.URL_KEY_SOURCE_URL, sourceUrl);

                // 返回登录页面
                response.sendRedirect(RouterLogin.LOGIN_VIEW);

                return false;

            }else {
                return true;
            }
        }
    }
}
